import { Suspense, useState, useEffect, useReducer } from 'react';
import { message } from 'antd';
import { GridContent } from '@ant-design/pro-layout';
import SalesCard from '@/components/StoreCommon';
import { getTimeDistance } from './utils/utils';
import styles from './style.less';
import { Select, Form, Input, DatePicker, Button } from 'antd';
import { storeList, queryDayRule, getAllStore, exportConsume } from './service';
import moment from 'moment';
import { handleData, saveFileAs } from '@/utils/utils';
import CreateForm from '@/pages/Home/component/CreateForm';
import ProTable from '@ant-design/pro-table';
import Access from '@/components/Access/Access';
const StoreAnalysis = () => {
  const [rangePickerValue, setRangePickerValue] = useState(getTimeDistance('year'));
  const [loading, setLoading] = useState();
  const [store, setStore] = useState([]);
  const [storeName, setStoreName] = useState();
  const [storeId, setStoreId] = useState();
  const [timer, setTimer] = useState();
  const [timerObj, setTimerObj] = useState();
  const [timerList, setTimerList] = useState();
  const [Convergence, setConvergence] = useState({});
  const [showState, setShowState] = useState('year');
  const [outModal, handleOutModal] = useState(false);
  const [storeArray, handleStoreArray] = useState([]);
  const initialState = {
    BillData: [],
  };
  const reducer = (state, { type, payload }) => {
    switch (type) {
      case 'Change':
        return {
          BillData: JSON.parse(JSON.stringify(payload.BillData)),
        };

      default:
        break;
    }
  };
  const [state, dispatch] = useReducer(reducer, initialState);
  const handleStore = () => {
    storeList()
      .then((res) => {
        const { code } = res;
        if (code === 0) {
          setStore(res.data);
        } else {
          message.error(res.message);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const handleAllStore = (payload, params) => {
    setLoading(true);
    const nowDate = handleData(new Date());
    params ? delete params.url : null;
    getAllStore(payload, params ? params : { date: nowDate })
      .then((res) => {
        const { code } = res;
        if (code === 0) {
          const { data } = res;
          let arr = JSON.parse(JSON.stringify(data));
          !data
            ? (arr = [])
            : arr.map((item) => {
                item.key = item.storeId;
              });

          let target = {
            storeName:'合计',
            backAmount:0,
            backCount:0,
            balanceConsumeAmount:0,
            balanceConsumeCount:0,
            cardConsumeAmount:0,
            cardConsumeCount:0,
            cashAmount:0,
            cashConsumeAmount:0,
            cashConsumeCount:0,
            cashOpenCardAmount:0,
            cashOpenCardCount:0,
            cashRechargeAmount:0,
            cashRechargeCount:0,
            codeConsumeAmount:0,
            codeConsumeCount:0,
            composeBalance:0,
            composeCount:0,
            composeIntegral:0,
            consumeAmount:0,
            consumeCount:0,
            costAmount:0,
            integralConsumeAmount:0,
            integralConsumeCount:0,
            openCardAmount:0,
            openCardCount:0,
            profit:0,
            profitAmount:0,
            rechargeAmount:0,
            rechargeCount:0,
            totalCurrentAmount:0,
            withdrawAmount:0,
            withdrawBalance:0,
            withdrawBalanceCount:0,
            withdrawCount:0,
            withdrawIntegral:0,
            withdrawIntegralCount:0,
          };
          arr.forEach((data)=>{
            target.backAmount+=Number(data.backAmount) ;
            target.backCount+=Number(data.backCount);
            target.balanceConsumeAmount+=Number(data.balanceConsumeAmount);
            target.balanceConsumeCount+=Number(data.balanceConsumeCount);
            target.cardConsumeAmount+=Number(data.cardConsumeAmount);
            target.cardConsumeCount+=Number(data.cardConsumeCount);
            target.cashAmount+=Number(data.cashAmount);
            target.cashConsumeAmount+=Number(data.cashConsumeAmount);
            target.cashConsumeCount+=Number(data.cashConsumeCount);
            target.cashOpenCardAmount+=Number(data.cashOpenCardAmount);
            target.cashOpenCardCount+=Number(data.cashOpenCardCount);
            target.cashRechargeAmount+=Number(data.cashRechargeAmount);
            target.cashRechargeCount+=Number(data.cashRechargeCount);
            target.codeConsumeAmount+=Number(data.codeConsumeAmount);
            target.codeConsumeCount+=Number(data.codeConsumeCount);
            target.composeBalance+=Number(data.composeBalance);
            target.composeCount+=Number(data.composeCount);
            target.composeIntegral+=Number(data.composeIntegral);
            target.consumeAmount+=Number(data.consumeAmount);
            target.consumeCount+=Number(data.consumeCount);
            target.costAmount+=Number(data.costAmount);
            target.integralConsumeAmount+=Number(data.integralConsumeAmount);
            target.integralConsumeCount+=Number(data.integralConsumeCount);
            target.openCardAmount+=Number(data.openCardAmount);
            target.openCardCount+=Number(data.openCardCount);
            target.profit+=Number(data.profit);
            target.profitAmount+=Number(data.profitAmount);
            target.rechargeAmount+=Number(data.rechargeAmount);
            target.rechargeCount+=Number(data.rechargeCount);
            target.totalCurrentAmount+=Number(data.totalCurrentAmount);
            target.withdrawAmount+=Number(data.withdrawAmount);
            target.withdrawBalance+=Number(data.withdrawBalance);
            target.withdrawBalanceCount+=Number(data.withdrawBalanceCount);
            target.withdrawCount+=Number(data.withdrawCount);
            target.withdrawIntegral+=Number(data.withdrawIntegral);
            target.withdrawIntegralCount+=Number(data.withdrawIntegralCount);
          });
          target.consumeAmount = target.consumeAmount.toFixed(2);
          target.balanceConsumeAmount = target.balanceConsumeAmount.toFixed(2);
          target.cardConsumeAmount = target.cardConsumeAmount.toFixed(2);
          target.cashAmount = target.cashAmount.toFixed(2);
          target.cashConsumeAmount = target.cashConsumeAmount.toFixed(2);
          target.cashOpenCardAmount = target.cashOpenCardAmount.toFixed(2);
          target.cashRechargeAmount = target.cashRechargeAmount.toFixed(2);
          target.codeConsumeAmount = target.codeConsumeAmount.toFixed(2);
          target.composeBalance = target.composeBalance.toFixed(2);
          target.composeIntegral = target.composeIntegral.toFixed(2);
          target.costAmount = target.costAmount.toFixed(2);
          target.integralConsumeAmount = target.integralConsumeAmount.toFixed(2);
          target.openCardAmount = target.openCardAmount.toFixed(2);
          target.profitAmount = target.profitAmount.toFixed(2);
          target.rechargeAmount = target.rechargeAmount.toFixed(2);
          target.totalCurrentAmount = target.totalCurrentAmount.toFixed(2);
          target.withdrawAmount = target.withdrawAmount.toFixed(2);
          target.withdrawBalance = target.withdrawBalance.toFixed(2);
          target.withdrawIntegral = target.withdrawIntegral.toFixed(2);
          let targets = [target].concat(arr);
          dispatch({
            type: 'Change',
            payload: {
              BillData: targets,
            },
          });
          setLoading(false);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const selectDate = (type) => {
    setRangePickerValue(getTimeDistance(type));
  };

  const handleRangePickerChange = (value) => {
    setRangePickerValue(value);
  };
  const onFinish = (payload) => {
    let list = {
      url: '',
      storeName: storeName,
      storeId: storeId,
      date: '',
    };
    let time = '';
    switch (showState) {
      case 'year':
        list.url = 'yearCount';
        time = timer ? timer : new Date().getFullYear();
        list.date = `${time}-01-01`;
        break;
      case 'month':
        list.url = 'monthCount';
        const nowDate = moment(new Date()).day(1).format('YYYY-MM-DD');
        const dateArray = nowDate.split('-');
        const startTimeMonth = moment(new Date(dateArray[0], Number(dateArray[1]) - 1, 1)).format(
          'YYYY-MM-DD',
        );
        time = timer ? timer : startTimeMonth;
        list.date = time;
        break;
      case 'week':
        list.url = 'weekCount';
        const nowDateWeek = moment(new Date()).day(1).format('YYYY-MM-DD');
        const dateArrayWeek = nowDateWeek.split('-');
        const startTimeMonthWeek = moment(
          new Date(dateArrayWeek[0], Number(dateArrayWeek[1]) - 1, 1),
        ).format('YYYY-MM-DD');
        time = timerList?.startTime ? timerList.startTime : startTimeMonthWeek;
        list.date = time;
        break;
      case 'day':
        list.url = 'dayCount';
        time = timer
          ? timer
          : new Date().getFullYear() +
            '-' +
            (new Date().getMonth() + 1) +
            '-' +
            new Date().getDate();
        list.date = time;
        break;
      default:
        break;
    }
    handleAllStore(list.url, list);
  };
  const handleTabSearch = (payload) => {
    let list = {
      url: '',
      storeName: storeName,
      storeId: storeId,
      date: '',
    };
    let time = '';
    switch (payload) {
      case 'year':
        list.url = 'yearCount';
        time = new Date().getFullYear();
        list.date = `${time}-01-01`;
        break;
      case 'month':
        list.url = 'monthCount';
        const nowDate = moment(new Date()).day(1).format('YYYY-MM-DD');
        const dateArray = nowDate.split('-');
        const startTimeMonth = moment(new Date(dateArray[0], Number(dateArray[1]) - 1, 1)).format(
          'YYYY-MM-DD',
        );
        time = startTimeMonth;
        list.date = time;
        break;
      case 'week':
        list.url = 'weekCount';
        const nowDateWeek = moment(new Date()).day(1).format('YYYY-MM-DD');
        const dateArrayWeek = nowDateWeek.split('-');
        const startTimeMonthWeek = moment(
          new Date(dateArrayWeek[0], Number(dateArrayWeek[1]) - 1, 1),
        ).format('YYYY-MM-DD');
        time = startTimeMonthWeek;
        list.date = time;
        break;
      case 'day':
        list.url = 'dayCount';
        time =
          new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate();
        list.date = time;
        break;
      default:
        break;
    }
    handleAllStore(list.url, list);
  };
  const handleChangeTab = (value) => {
    switch (value) {
      case 'year':
        setShowState('year');
        setTimer();
        setTimerObj();
        break;
      case 'month':
        setShowState('month');
        setTimer();
        setTimerObj();
        break;
      case 'week':
        setShowState('week');
        setTimer();
        setTimerObj();
        break;
      case 'day':
        setShowState('day');
        setTimer();
        setTimerObj();
        break;

      default:
        break;
    }
    handleTabSearch(value);
  };

  const selectDay = (date, dateString) => {
    if (date) {
      setTimer(dateString);
      setTimerObj(date);
    }
  };
  const onWeekChange = (date, dateString) => {
    if (date) {
      const startTime = moment(date).day(0).format('YYYY-MM-DD');
      const endTime = moment(date).day(6).format('YYYY-MM-DD');
      setTimerList({
        startTime,
        endTime,
      });
      setTimerObj(date);
      setTimer(date);
    }
  };
  const onMonthChange = (date, dateString) => {
    if (date) {
      const startTime = date.startOf("month").format("YYYY-MM-DD");
      setTimer(startTime);
      setTimerObj(date);
    }
  };
  const onYearChange = (date, dateString) => {
    if (date) {
      setTimer(dateString);
      setTimerObj(date);
    }
  };
  const onChange = (e) => {
    if (e){
      setStoreName(e.label);
      setStoreId(e.key);
    }else {
      setStoreId(null);
    }
  };

  useEffect(() => {
    handleStore();
    handleAllStore('yearCount');
  }, []);
  const formItemLayout = {
    labelCol: { span: 12 },
    wrapperCol: { span: 16 },
  };
  const outColumns = [
    {
      title: '导出时间',
      dataIndex: 'date',
      renderFormItem: () => {
        switch (showState) {
          case 'year':
            return (
              <DatePicker
                picker="year"
                allowClear={false}
                value={timerObj}
                onChange={onYearChange}
              />
            );
          case 'month':
            return (
              <DatePicker
                picker="month"
                allowClear={false}
                value={timerObj}
                onChange={onMonthChange}
              />
            );

          case 'week':
            return (
              <DatePicker
                picker="week"
                allowClear={false}
                value={timerObj}
                onChange={onWeekChange}
              />
            );

          case 'day':
            return (
              <DatePicker
                allowClear={false}
                disabledDate={(current) => {
                  return current > moment(new Date());
                }}
                showToday
                value={timerObj}
                onChange={selectDay}
              />
            );
          default:
            break;
        }
      },
    },
    {
      title: '导出店铺',
      dataIndex: 'storeName',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <Select
            labelInValue
            placeholder="选择店铺"
            allowClear
            showSearch
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            { store&&store.length>0?store.map((item) => {
              return (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              );
            }):null}
          </Select>
        );
      },
    },
  ];
  return (
    <GridContent>
      <Form
        name="basic"
        {...formItemLayout}
        onFinish={onFinish}
        layout={'inline'}
        className={styles.form_div}
      >
        <Form.Item label="店铺名称" name="storeName">
          <Select
            labelInValue
            showSearch
            style={{ width: 200 }}
            placeholder="请输入店铺"
            optionFilterProp="children"
            // onSearch={onSearch}
            onChange={onChange}
            allowClear
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {store&&store.length>0?store.map((item, index) => {
              return (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              );
            }):null}
          </Select>
        </Form.Item>
      </Form>
      <Suspense fallback={null}>
        <SalesCard
          rangePickerValue={rangePickerValue}
          salesData={state}
          onSearch={
            <Button type="primary" htmlType="submit" onClick={onFinish}>
              查询
            </Button>
          }
          onExport={
            <Access accessKey={"@exportStoreCountData"}>
              <Button danger htmlType="submit" onClick={() => handleOutModal(true)}>
                导出店铺统计数据
              </Button>
            </Access>
          }
          handleRangePickerChange={handleRangePickerChange}
          loading={loading}
          selectDate={selectDate}
          showDate={showState}
          handleChangeTab={handleChangeTab}
          selectDay={selectDay}
          onYearChange={onYearChange}
          onWeekChange={onWeekChange}
          Convergence={Convergence}
          year={timerObj}
          month={timerObj}
          day={timerObj}
          week={timerObj}
          style={styles}
          onMonthChange={onMonthChange}
        />
      </Suspense>
      <CreateForm
        title={'导出信息'}
        width={800}
        footer={null}
        onCancel={() => handleOutModal(false)}
        modalVisible={outModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            let list = {
              type: '',
              storeId: value.storeName?value.storeName.key:'',
              date: '',
            };
            let time = '';
            switch (showState) {
              case 'year':
                list.type = 'year';
                time = timer ? timer : new Date().getFullYear();
                list.date = `${time}-01-01`;
                break;
              case 'month':
                list.type = 'month';
                const nowDate = moment(new Date()).day(1).format('YYYY-MM-DD');
                const dateArray = nowDate.split('-');
                const startTimeMonth = moment(
                  new Date(dateArray[0], Number(dateArray[1]) - 1, 1),
                ).format('YYYY-MM-DD');
                time = timer ? timer : startTimeMonth;
                list.date = time;
                break;
              case 'week':
                list.type = 'week';
                const nowDateWeek = moment(new Date()).day(1).format('YYYY-MM-DD');
                const dateArrayWeek = nowDateWeek.split('-');
                const startTimeMonthWeek = moment(
                  new Date(dateArrayWeek[0], Number(dateArrayWeek[1]) - 1, 1),
                ).format('YYYY-MM-DD');
                time = timerList?.startTime ? timerList.startTime : startTimeMonthWeek;
                list.date = time;
                break;
              case 'day':
                list.type = 'day';
                time = timer
                  ? timer
                  : new Date().getFullYear() +
                    '-' +
                    (new Date().getMonth() + 1) +
                    '-' +
                    new Date().getDate();
                list.date = time;
                break;
              default:
                break;
            }
            if (!list.date) {
              message.warning('请选择导出excel时间');
            } else {
              exportConsume(list)
                .then((res) => {
                  if (res) {
                    saveFileAs(
                      res,'店铺订单统计');
                  } else {
                    message.info(res.message);
                  }
                })
                .catch((err) => {
                  message.error(err);
                  console.log(err);
                });
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={outColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
    </GridContent>
  );
};

export default StoreAnalysis;
